const koa = require('koa')
const Router = require('koa-router')
const bodyParser = require('koa-bodyparser')
const Swig = require('koa-swig')
const co = require('co')
const path = require('path')

let todoList = [
    { id: 1, mes: 'TODO-1', done: true },
    { id: 2, mes: 'TODO-2', done: false },
    { id: 3, mes: 'TODO-3', done: false },
]

const app = new koa()
const router = new Router()
app.context.render = co.wrap(Swig({
    root: path.join(__dirname, 'static'),
    autoescape: true,
    cache: false,
    ext: 'html'
}))
app.use(bodyParser())  // 注册解析器  通过ctx.request.body 获取参数

router.get('/', async (ctx, next) => {
    ctx.body = await ctx.render('index.html', {
        todoList
    })
})

/** get方式  添加 */
// router.get('/add',async ctx=>{
//     console.log(ctx.query.title)
//     let status = ''
//     let flag = todoList.find(item=>{
//         return item.mes === ctx.query.title
//     })
//     if(flag){
//         status = '添加失败,请勿重复添加'
//     }else{
//         todoList.push({
//             id:todoList[todoList.length-1].id+1,
//             mes:ctx.query.title,
//             done:false
//         })
//         console.log(todoList)
//         status = '添加成功'
//     }
//     ctx.body = await ctx.render('add.html',{status})
// })

/** post方式  添加 */
router.post('/add', async ctx => {
    console.log(ctx.request.body)
    let status = ''
    let flag = todoList.find(item => {
        return item.mes === ctx.request.body.title
    })
    if (flag) {
        status = '添加失败,请勿重复添加'
    } else {
        todoList.push({
            id: todoList[todoList.length - 1].id + 1,
            mes: ctx.request.body.title,
            done: false
        })
        status = '添加成功'
    }
    ctx.body = await ctx.render('add.html', { status })
})

router.get('/remove/:id', ctx => {
    let i = todoList.findIndex(item => {
        return item.id == ctx.params.id
    })
    todoList.splice(i, 1)
    ctx.redirect('/')
})

router.get('/change/:id', ctx => {
    todoList.forEach((item,i)=>{
        if(item.id==ctx.params.id){
            todoList[i].done = !todoList[i].done
        }
    })
    ctx.redirect('/')
})

app.use(router.routes())

app.listen(80, '127.0.0.1')